<template>
  <transition name="fade" @after-leave="$emit('destroy')" appear type="animation">
    <div class="wx-alert" :style="{'top': top}" v-show="visible">
      <div class="wx-alert__main">
        <div
          class="wx-alert__main__content"
          :class="className"
        >{{ content }}</div>
      </div>
    </div>  
  </transition>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, PropType, computed } from 'vue'
import type { alertType } from './alert.type'

export default defineComponent({
  props: {
    type: {
      type: String as PropType<alertType>
    },
    duration: {
      type: Number,
      default: 1000
    },
    content: {
      type: [String, Number],
      default: ''
    },
    top: {
      type: String
    }
  },
  setup(props) {
    const className = computed(() => `wx-alert__main__content__${props.type}`)

    const visible = ref(true)

    let timer: any = null

    onMounted(() => {
      startTimer()
      visible.value = true
    })

    const startTimer = () => {
      if (props.duration > 0) {
        timer = setTimeout(() => {
          close()
        }, props.duration)
      }
    }

    const close = () => {
      visible.value = false
      clearTimeout(timer)
      timer = null
    }

    return {
      className,
      visible
    }
  }
})
</script>

<style scoped>
.fade-enter-from, .fade-leave-to {
  animation: msgbox-fade-out 1s linear;
}
/* .fade-leave-from, .fade-enter-to {
  animation: msgbox-fade-in 1s linear;
} */

@keyframes msgbox-fade-in {
  0% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
  100% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}

@keyframes msgbox-fade-out {
  0% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  100% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
}
</style>